package shanpao.imohoo.com.testdb;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

import static shanpao.imohoo.com.testdb.SpDBHelper.SP_TABLE_NAME;

public class CacheDBHelper extends SQLiteOpenHelper {
    private static CacheDBHelper instance;
    public static final String TABLE_NAME = "table_cache";
    public static final String DB_NAME = "cache";
    public static final int DB_VERSION = 11;
    public static final long DEFAULT_TIME = 2 * 24 * 60 * 60 * 1000;

    public CacheDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    private static CacheDBHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (CacheDBHelper.class) {
                if (instance == null) {
                    instance = new CacheDBHelper(context);
                    instance.deleteDB();
                }
            }
        }
        return instance;
    }

    public static void destoryInstance() {
        if (instance != null) {
            instance.close();
        }
    }

    public static CacheDBHelper getInstance() {
        if (instance == null)// cache_net  cache
            return CacheDBHelper.getInstance(App.getInstance());
        return instance;
    }

    private AtomicInteger mOpenCounter = new AtomicInteger();
    private SQLiteDatabase mDatabase;

    public synchronized SQLiteDatabase openDatabase() {
        if (mOpenCounter.incrementAndGet() == 1) {
            // Opening new database
            mDatabase = getWritableDatabase();
        }
        return mDatabase;
    }

    public synchronized void closeDatabase() {
        if (mOpenCounter.decrementAndGet() == 0) {
            // Closing database
            if (mDatabase != null) {
                mDatabase.close();
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        create(db);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        update(db, oldVersion, newVersion);
    }

    public static synchronized void create(SQLiteDatabase db) {
        try {
            db.beginTransaction();

            db.execSQL("create table if not exists " + TABLE_NAME
                    + "(id Integer primary key AUTOINCREMENT,"
                    + "apidata text,"
                    + "result text,"
                    + "update_time Integer)");

            db.execSQL("create table if not exists " + SP_TABLE_NAME
                    + "(id Integer primary key AUTOINCREMENT,"
                    + "user_id Integer,"
                    + "area_id Integer,"
                    + "click_time Integer,"
                    + "extra text,"
                    + "status Integer)");// 0无,1上传中,-1上传完成
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }

    public static synchronized void update(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 清除两天前的过期数据
     */
    private void deleteDB() {
        SQLiteDatabase db = null;
        try {
            db = CacheDBHelper.getInstance().openDatabase();
            db.beginTransaction();
            long time = System.currentTimeMillis();
            time -= DEFAULT_TIME;
            //删除
            db.execSQL("delete from " + TABLE_NAME + " where update_time<? and update_time<>0",
                    new Object[]{time});

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (db != null) {
                    db.endTransaction();
                    CacheDBHelper.getInstance().closeDatabase();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public static boolean insertDB(Cache cache) {
        SQLiteDatabase db = null;
        try {
            db = CacheDBHelper.getInstance().openDatabase();
//            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where apidata=?",
//                    new String[]{cache.getApidata()});
//            boolean isDel = false;
//            boolean isUpdate = false;
//            if (cursor != null && cursor.getCount() > 1) {
//                isDel = true;
//            }
//            if (cursor != null && cursor.getCount() == 1) {
//                isUpdate = true;
//            }
//            if (cursor != null) {
//                cursor.close();
//            }

            db.beginTransaction();

//            //删除
//            if (isDel) {
//                db.execSQL("delete from " + TABLE_NAME + " where apidata=?",
//                        new Object[]{cache.getApidata()});
//            }
//            if (isUpdate) {
//                db.execSQL("update " + TABLE_NAME + " set result = ?,update_time=? where apidata = ?",
//                        new Object[]{cache.getResult(), cache.getUpdate_time(), cache.getApidata()});
//            } else {
                db.execSQL("insert into " + TABLE_NAME + " (apidata,result,update_time) values(?,?,?)",
                        new Object[]{cache.getApidata(), cache.getResult(), cache.getUpdate_time()});
//            }
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (db != null) {
                    db.endTransaction();
                    CacheDBHelper.getInstance().closeDatabase();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static Cache getDB(String apidata) {
        SQLiteDatabase db = null;
        try {
            db = CacheDBHelper.getInstance().openDatabase();
            Cursor cursor = db.rawQuery("select * from " + TABLE_NAME + " where apidata=?",
                    new String[]{apidata});
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();

                Cache cache = new Cache();
                cache.setId(cursor.getInt(cursor.getColumnIndex("id")));
                cache.setApidata(cursor.getString(cursor.getColumnIndex("apidata")));
                cache.setResult(cursor.getString(cursor.getColumnIndex("result")));
                cache.setUpdate_time(cursor.getLong(cursor.getColumnIndex("update_time")));

                // 关闭游标
                cursor.close();

                return cache;
            }
            if (cursor != null) {
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (db != null) {
                    CacheDBHelper.getInstance().closeDatabase();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static boolean deleteCacheDB(String apidata) {
        SQLiteDatabase db = null;
        try {
            db = CacheDBHelper.getInstance().openDatabase();

            db.beginTransaction();

            db.execSQL("delete from " + TABLE_NAME + " where apidata=?",
                    new Object[]{apidata});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (db != null) {
                    db.endTransaction();
                    CacheDBHelper.getInstance().closeDatabase();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static Cache getDB(HashMap<String, String> bodyMap) {
        return CacheDBHelper.getDB(bodyMap.get("CACHEAPI"));
    }

    public static Cache saveCache(String key, String value, int minute) {
        Cache cache = new Cache();
        // cache 默认删除2天以前的东西
        if (minute != 0) {
            cache.setUpdate_time(System.currentTimeMillis() - DEFAULT_TIME + minute * 60 * 1000L);
        } else {
            cache.setUpdate_time(0);// 不过期
        }
        cache.setResult(value);
        cache.setApidata(key);
        CacheDBHelper.insertDB(cache);
        return cache;
    }

    public static <T> T getCache(String key, Class<T> clazz) {
        Cache cache = getDB(key);
        if (cache == null) {
            return null;
        }
        // 过期了就放弃
        if (cache.getUpdate_time() != 0 && System.currentTimeMillis() - DEFAULT_TIME > cache.getUpdate_time()) {
            return null;
        }
        Type type = clazz.getGenericSuperclass();
        if (clazz == Cache.class) {
            return (T) cache;
        } else if (clazz == String.class) {
            return (T) cache.getResult();
        }
        return null;
    }

    public static void deleteCache(String key) {
        CacheDBHelper.deleteCacheDB(key);
    }


    public void insert(SpPoint spPoint) {
        SQLiteDatabase db = CacheDBHelper.getInstance().openDatabase();
        try {
            db.beginTransaction();

            db.execSQL("insert into " + SP_TABLE_NAME + " (user_id,area_id,click_time,extra,status) values(?,?,?,?,?)",
                    new Object[]{
                            spPoint.getUser_id(),
                            spPoint.getArea_id(),
                            spPoint.getClick_time(),
                            spPoint.getExtra(),
                            0
                    });
//            Cursor cursor = db.rawQuery("select last_insert_rowid() rowid;", new String[]{});
//            cursor.moveToFirst();
//            spPoint.setId(cursor.getInt(0));
//            cursor.close();
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                db.endTransaction();
                CacheDBHelper.getInstance().closeDatabase();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
